package com.artifex.mupdf.viewer.app

import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import timber.log.Timber
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class CrashReportingTree(private val context: Context) : Timber.Tree() {
    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        if (priority >= Log.ERROR) {
            val crashReport = buildCrashReport(message, t)

            // Save to file or send to server if needed
//            saveCrashReport(crashReport)

            // Show pretty crash activity
            Handler(Looper.getMainLooper()).post {
                showCrashActivity(crashReport)
            }
        }
    }

    private fun buildCrashReport(message: String, throwable: Throwable?): String {
        return buildString {
            append("=== CRASH REPORT ===\n")
            append("Time: ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())}\n")
            append("Message: $message\n")

            throwable?.let {
                append("\nStack Trace:\n")
                append(Log.getStackTraceString(it))
            }

            append("\n\nDevice Info:\n")
            append("Model: ${Build.MODEL}\n")
            append("Brand: ${Build.BRAND}\n")
            append("Android Version: ${Build.VERSION.RELEASE}\n")
//            append("App Version: ${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})\n")
        }
    }

//    private fun saveCrashReport(report: String) {
//        try {
//            val file = File(context.getExternalFilesDir(null), "crash_reports")
//            if (!file.exists()) file.mkdirs()
//
//            val crashFile = File(file, "crash_${System.currentTimeMillis()}.txt")
//            crashFile.writeText(report)
//        } catch (e: Exception) {
//            Timber.e(e, "Failed to save crash report")
//        }
//    }

    private fun showCrashActivity(report: String) {
        try {
            CrashReportActivity.start(context, report)
        } catch (e: Exception) {
            Timber.e(e, "Failed to show crash activity")
        }
    }
}